package com.itsu.commons.utils;

import cn.hutool.core.lang.UUID;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;

public class OssUtil {

    private static String accessKey_id;
    private static String accessKey_secret;
    private static String endpoint;
    private static String bucketName;
    private static String picurl;


    static {
        Properties properties = new Properties();
        try {
            properties.load(OssUtil.class.getClassLoader().getResourceAsStream("alibabaServer.properties"));
            accessKey_secret = properties.getProperty("oss.access_key_secret");
            accessKey_id = properties.getProperty("oss.access_key_id");
            endpoint = properties.getProperty("oss.endpoint");
            bucketName = properties.getProperty("oss.bucketname");
            picurl = properties.getProperty("oss.picurl");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String saveImage(byte[] imageData, String fileSuffixName) {

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey_id,accessKey_secret);


        String filePath = getFilePath(fileSuffixName);
        ossClient.putObject(bucketName, filePath, new ByteArrayInputStream(imageData));

        ossClient.shutdown();
        return picurl + filePath;
    }

    public static String getFilePath(String fileSuffixName) {
        Date date = new Date();
        return "images/" + ( date.getYear()+ 1900) + "/"
                + date.getMonth() + "/" + date.getDate() + "/"
                + UUID.fastUUID().toString(true) + "." + fileSuffixName;
    }


}
